<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="translate(title)"
    width="800px"
    @close="close"
  >
    <el-form
      ref="formRef"
      v-loading="saveLoading"
      element-loading-background="rgba(122, 122, 122, 0.8)"
      label-width="160px"
      :model="form"
      :rules="rules"
    >
      <!-- <el-form-item label="公司主键：" prop="fullName">
        <el-tree-select
          v-model="form.companyId"
          :check-strictly="true"
          :data="tree"
          node-key="id"
          :props="defaultProps"
          :render-after-expand="false"
          show-checkbox
        />
      </el-form-item> -->
      <el-form-item :label="translate('物资类别') + '：'">
        <el-tree-select
          v-model="form.icid"
          :check-strictly="true"
          :data="data"
          node-key="id"
          :props="defaultProps"
          :render-after-expand="false"
          show-checkbox
        />
      </el-form-item>
      <el-form-item :label="translate('物资编码') + '：'" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item :label="translate('物资名称') + '：'" prop="fullName">
        <el-input v-model="form.fullName" />
      </el-form-item>
      <!-- <el-form-item :label="translate('物资简称') + '：'">
        <el-input v-model="form.abbreviation" />
      </el-form-item> -->
      <el-form-item :label="translate('单位') + '：'">
        <el-input v-model="form.whUnit" />
      </el-form-item>
      <el-form-item :label="translate('存放地点') + '：'">
        <el-input v-model="form.storageLocation" />
      </el-form-item>
      <el-form-item :label="translate('规格型号') + '：'">
        <el-input v-model="form.spec" />
      </el-form-item>
      <el-form-item :label="translate('计量单位') + '：'">
        <el-input v-model="form.unit" />
      </el-form-item>
      <el-form-item :label="translate('单价') + '：'">
        <el-input v-model="form.price" />
      </el-form-item>
      <el-form-item :label="translate('仓储管理员') + '：'">
        <el-input v-model="form.whManage" />
      </el-form-item>
      <el-form-item :label="translate('电话') + '：'">
        <el-input v-model="form.whManageTel" />
      </el-form-item>
      <el-form-item :label="translate('供应厂家') + '：'">
        <el-input v-model="form.SupName" />
      </el-form-item>
      <el-form-item :label="translate('显示顺序') + '：'">
        <el-input v-model="form.sortCode" />
      </el-form-item>
      <el-form-item :label="translate('是否能用') + '：'">
        <el-radio v-model="form.stockStatus" label="是">是</el-radio>
        <el-radio v-model="form.stockStatus" label="否">否</el-radio>
      </el-form-item>
      <el-form-item :label="translate('备注') + '：'">
        <el-input
          v-model="form.remark"
          autosize
          :placeholder="translate('请输入备注')"
          type="textarea"
        />
      </el-form-item>
      <el-form-item :label="translate('附件') + '：'">
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          :action="action"
          :auto-upload="false"
          :before-upload="beforeUpload"
          class="upload-demo"
          drag
          :headers="headers"
          multiple
          name="fileInput"
          :on-error="uploadFilled"
          :on-success="uploadSuccessed"
          style="width: 200px; height: 200px"
        >
          <!-- <el-image
            :fit="[fit]"
            src="https://dss2.bdstatic.com/8_V1bjqh_Q23odCf/pacific/1994074134.jpg?x=0&y=0&h=150&w=242&vh=150.00&vw=242.00&oh=150.00&ow=242.00"
            style="width: 100px; height: 100px"
          /> -->
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">{{ translate('上传文件') }}</div>
        </el-upload>
      </el-form-item>

      <!-- <el-form-item label="物资类别父级主键：">
        <el-tree-select
          v-model="form.parentId"
          :check-strictly="true"
          :data="parentList"
          node-key="id"
          :props="defaultProps"
          :render-after-expand="false"
          show-checkbox
        />
      </el-form-item> -->
    </el-form>
    <file v-if="form.uniqueCode" ref="editFile" :form-id="form.uniqueCode" />
    <template #footer>
      <el-button @click="close">{{ translate('取消') }}</el-button>
      <el-button :loading="saveLoading" type="primary" @click="save">
        {{ translate('确定') }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { doEdit, gets, getFlieList, getTreeList } from '@/api/item'
  import { baseURL } from '@/config'
  import { useUserStore } from '@/store/modules/user'
  import { translate } from '@/i18n'
  export default defineComponent({
    name: 'ItemEdit',
    components: {
      File: defineAsyncComponent(() => import('@/views/components/file')),
    },
    props: {
      tree: {
        type: Array,
        default: () => [],
      },
      parentList: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['fetchData'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const { token } = useUserStore()
      const state = reactive({
        formRef: null,
        editFile: null,
        uploadRef: null,
        action: `${baseURL}/WF_Document/UploadFile`,
        headers: { Authorization: `Bearer ${token}` },
        fileList: [],
        random: '',
        dialogVisibleImg: '',
        dialogImageUrl: '',
        data: [],
        radio: '是',
        defaultProps: {
          children: 'ChildNodes',
          label: 'text',
        },
        docList: [],
        queryForm: {
          CompanyId: 'string',
          departmentId: 'string',
          nature: 'string',
        },
        form: {},
        rules: {
          code: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请输入物资编码'),
            },
          ],
          // companyId: [
          //   { required: true, trigger: 'blur', message: '请选择公司主键' },
          // ],
          icid: [
            {
              required: true,
              trigger: 'change',
              message: translate('请选择物资类别'),
            },
          ],
          fullName: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请输入物资名称'),
            },
          ],
          price: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请输入单价'),
            },
          ],
          CompanyId: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请选择所在公司'),
            },
          ],
        },
        title: '',
        dialogFormVisible: false,
        saveLoading: false,
      })

      //获取详情数据
      const getS = async () => {
        state.listLoading = true
        const {
          data: { data },
        } = await gets(state.queryForm)
        if (!data.stockStatus) {
          data.stockStatus = '否'
        }
        state.form = data
        state.listLoading = false
      }
      const showEdit = (row, type) => {
        nextTick(() => {
          state['uploadRef']?.clearFiles()
        })
        if (type != 'edit') {
          state.title = '添加'
          // state.form.UserId = ''
        } else {
          state.title = '编辑'
          // state.queryForm.companyId = row.CompanyId
          state.queryForm.iid = row.IID
          getS()
        }
        gettreelist()
        state.dialogFormVisible = true
      }
      const S4 = () => {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
      }
      const getRandom = () => {
        return `${S4() + S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`
      }
      const beforeUpload = (val) => {
        state.action = `${baseURL}/WF_Document/UploadFile?TypeName=Wms_Item&FormId=${state.form.uniqueCode}`
      }
      let count = 0
      const uploadSuccessed = async (val) => {
        if (val.code == 200) {
          count++
          if (count === state.fileList.length) {
            const { message } = await doEdit(state.form)
            state.saveLoading = false
            $baseMessage(message, 'success', 'vab-hey-message-success')
            emit('fetchData')
            count = 0
            close()
          }
        } else {
          state.saveLoading = false
          count = 0
          $baseMessage(val.message, 'error', 'vab-hey-message-error')
        }
      }
      const uploadFilled = () => {
        state.saveLoading = false
      }
      const getflielist = async (row) => {
        state.listLoading = true
        const {
          data: { data },
        } = await getFlieList({
          formId: row,
        })
        state.docList = data
      }
      const gettreelist = async (row) => {
        state.listLoading = true
        const {
          data: { data },
        } = await getTreeList({})
        state.data = JSON.parse(data)
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {}
        state.dialogFormVisible = false
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            if (state.fileList.length) {
              if (!state.form.uniqueCode) {
                state.form.uniqueCode = getRandom()
              }
              state.saveLoading = true
              state['uploadRef'].submit()
            } else {
              state.saveLoading = true
              const { message } = await doEdit(state.form)
              state.saveLoading = false
              $baseMessage(message, 'success', 'vab-hey-message-ssuccess')
              close()
              emit('fetchData')
            }
          }
        })
      }
      return {
        ...toRefs(state),
        showEdit,
        getS,
        close,
        save,
        uploadSuccessed,
        beforeUpload,
        S4,
        getRandom,
        getflielist,
        gettreelist,
        uploadFilled,
        translate,
      }
    },
  })
</script>
<style lang="scss" scoped>
  .el-form {
    display: flex;
    flex-flow: wrap;
    justify-content: left;
  }
  ::v-deep .el-form .el-input {
    width: 214px !important;
  }
  .el-form-item {
    width: 380px;
  }
  ::v-deep .el-form-item__content {
    align-items: baseline !important;
  }
</style>
